
using System;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace ServiceHost
{
    [DataContract]
    public class Coordinate : IEquatable<Coordinate>
    {
        [DataMember] public double X;
        [DataMember] public double Y;

        public double Distance(Coordinate destination)
        {
            if (destination == null)
                return 0;

            //L= SQRT(ABS(SQR(X1-X2)) + ABS(SQR(Y1-Y2)))
            var res = Math.Sqrt(Math.Abs(Math.Pow(this.X - destination.X, 2)) + Math.Abs(Math.Pow(this.Y - destination.Y, 2)));

            System.Diagnostics.Debug.WriteLine("Source: " + this.X + " " + this.Y + " Dest: " + destination.X + " " + destination.Y + " Dist: " + res);

            return res;
        }

        public bool IsTooClose(Coordinate x1, Coordinate x2, double distance)
        {
            //Check start and end points
            if (x1 == null)
            {
                return this.Distance(x2) < distance;
            }

            if (x2 == null)
            {
                return this.Distance(x1) < distance;
            }

            //L1 - (L2 + l3) < 10
            var l1 = x1.Distance(x2);
            var l2 = this.Distance(x1);
            var l3 = this.Distance(x2);

            var d = (l2 + l3) - l1;

            Debug.WriteLine("IsTooClose: {0}", d);

            return d < distance;
        }

        public Coordinate(double x, double y)
        {
            X = x;
            Y = y;
        }

        public Coordinate()
        {
            
        }

        //-11.608 133.068
        public Coordinate(string coord)
        {
            if (!string.IsNullOrEmpty(coord))
            {
                var s = coord.Split(' ');
                Y = Double.Parse(s[0]);
                X = Double.Parse(s[1]);
            }
        }

        public bool Equals(Coordinate other)
        {
            return other.X == this.X && other.Y == this.Y;
        }
    }

}